<template>
  <div class="bg-white rounded-lg shadow-sm p-4 sm:p-6">
    <!-- 移动端：上下布局 | 桌面端：左右布局 -->
    <div class="flex flex-col lg:flex-row items-center gap-6">
      <!-- 分数展示区 -->
      <div class="flex-shrink-0 w-full lg:w-auto">
        <div class="text-center">
          <div 
            :class="[
              'text-5xl sm:text-6xl lg:text-7xl font-bold transition-all duration-1000',
              scoreColorClass
            ]"
          >
            {{ displayScore }}
          </div>
          <div class="text-gray-500 text-xs sm:text-sm mt-2">总分</div>
          <div class="mt-3 sm:mt-4 px-3 sm:px-4 py-1 rounded-full text-xs sm:text-sm font-medium inline-block" :class="scoreBadgeClass">
            {{ scoreLevel }}
          </div>
        </div>
      </div>

      <!-- 雷达图区域 -->
      <div class="flex-1 w-full">
        <!-- Canvas容器 - 响应式 -->
        <div class="relative flex justify-center">
          <canvas 
            ref="radarCanvas" 
            :width="canvasWidth" 
            :height="canvasHeight"
            class="max-w-full h-auto"
          ></canvas>
        </div>
        
        <!-- 维度说明 - 移动端优化 -->
        <div class="mt-4 grid grid-cols-1 sm:grid-cols-3 gap-2 sm:gap-3 text-xs sm:text-sm">
          <div v-for="(value, key) in dimensionScores" :key="key" class="flex items-center justify-between sm:justify-start bg-gray-50 sm:bg-transparent px-3 py-2 sm:p-0 rounded-lg sm:rounded-none">
            <div class="flex items-center gap-2">
              <div class="w-2 h-2 sm:w-3 sm:h-3 rounded-full flex-shrink-0" :style="{ backgroundColor: getDimensionColor(key) }"></div>
              <span class="text-gray-600">{{ getDimensionName(key) }}</span>
            </div>
            <span class="font-medium text-gray-900">{{ value }}分</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';

/**
 * ScoreDisplay 组件
 * 展示作文批改的总分和各维度评分雷达图
 */

// ==================== Props ====================
const props = defineProps({
  /**
   * 评分详细数据
   * @type {{ content_meaning?: number, language_expression?: number, structure_skills?: number, total_score: number }}
   */
  scoreBreakdown: {
    type: Object,
    required: true,
    default: () => ({ total_score: 0 }),
  },
  
  /**
   * 是否显示动画
   */
  animated: {
    type: Boolean,
    default: true,
  },
});

// ==================== Refs ====================
const radarCanvas = ref(null);
const displayScore = ref(0);

// 响应式Canvas尺寸
const canvasWidth = ref(320);
const canvasHeight = ref(240);

// ==================== Computed ====================

/**
 * 分数对应的颜色类名
 * < 60: 红色, 60-79: 黄色, 80-89: 蓝色, 90+: 绿色
 */
const scoreColorClass = computed(() => {
  const score = props.scoreBreakdown.total_score || 0;
  if (score < 60) return 'text-red-500';
  if (score < 80) return 'text-yellow-500';
  if (score < 90) return 'text-blue-500';
  return 'text-green-500';
});

/**
 * 分数徽章样式
 */
const scoreBadgeClass = computed(() => {
  const score = props.scoreBreakdown.total_score || 0;
  if (score < 60) return 'bg-red-100 text-red-800';
  if (score < 80) return 'bg-yellow-100 text-yellow-800';
  if (score < 90) return 'bg-blue-100 text-blue-800';
  return 'bg-green-100 text-green-800';
});

/**
 * 分数等级文本
 */
const scoreLevel = computed(() => {
  const score = props.scoreBreakdown.total_score || 0;
  if (score < 60) return '需加强';
  if (score < 70) return '及格';
  if (score < 80) return '良好';
  if (score < 90) return '优秀';
  return '卓越';
});

/**
 * 各维度分数
 */
const dimensionScores = computed(() => {
  const breakdown = props.scoreBreakdown;
  
  // 根据学段不同，维度名称可能不同
  // 这里统一处理，返回实际存在的维度
  const scores = {};
  
  // 通用维度映射
  if (breakdown.content_meaning !== undefined) {
    scores.content = breakdown.content_meaning;
  }
  if (breakdown.language_expression !== undefined) {
    scores.language = breakdown.language_expression;
  }
  if (breakdown.structure_skills !== undefined) {
    scores.structure = breakdown.structure_skills;
  }
  
  // 小学特有维度
  if (breakdown.basic_norms !== undefined) {
    scores.basic = breakdown.basic_norms;
  }
  if (breakdown.content_structure !== undefined) {
    scores.content_structure = breakdown.content_structure;
  }
  
  // 高中特有维度
  if (breakdown.depth_logic !== undefined) {
    scores.depth = breakdown.depth_logic;
  }
  if (breakdown.creativity_innovation !== undefined) {
    scores.creativity = breakdown.creativity_innovation;
  }
  
  return scores;
});

// ==================== Methods ====================

/**
 * 获取维度显示名称
 */
const getDimensionName = (key) => {
  const names = {
    content: '内容',
    language: '语言',
    structure: '结构',
    basic: '基础',
    content_structure: '内容结构',
    depth: '深度',
    creativity: '创意',
  };
  return names[key] || key;
};

/**
 * 获取维度对应的颜色
 */
const getDimensionColor = (key) => {
  const colors = {
    content: '#3b82f6',      // blue
    language: '#10b981',     // green
    structure: '#f59e0b',    // amber
    basic: '#8b5cf6',        // violet
    content_structure: '#ec4899', // pink
    depth: '#06b6d4',        // cyan
    creativity: '#f43f5e',   // rose
  };
  return colors[key] || '#6b7280';
};

/**
 * 动画显示分数
 */
const animateScore = () => {
  if (!props.animated) {
    displayScore.value = props.scoreBreakdown.total_score || 0;
    return;
  }
  
  const targetScore = props.scoreBreakdown.total_score || 0;
  const duration = 1000; // 1秒
  const fps = 60;
  const frames = duration / (1000 / fps);
  const increment = targetScore / frames;
  
  let currentFrame = 0;
  
  const animate = () => {
    currentFrame++;
    displayScore.value = Math.min(
      Math.round(increment * currentFrame),
      targetScore
    );
    
    if (currentFrame < frames) {
      requestAnimationFrame(animate);
    }
  };
  
  animate();
};

/**
 * 更新Canvas尺寸
 */
const updateCanvasSize = () => {
  if (typeof window === 'undefined') return;
  
  // 根据屏幕宽度调整Canvas尺寸
  const width = window.innerWidth;
  if (width < 640) { // 移动端
    canvasWidth.value = Math.min(width - 80, 320);
    canvasHeight.value = 240;
  } else if (width < 1024) { // 平板
    canvasWidth.value = 360;
    canvasHeight.value = 260;
  } else { // 桌面端
    canvasWidth.value = 400;
    canvasHeight.value = 280;
  }
};

/**
 * 绘制雷达图
 */
const drawRadarChart = () => {
  const canvas = radarCanvas.value;
  if (!canvas) return;
  
  const ctx = canvas.getContext('2d');
  const centerX = canvasWidth.value / 2;
  const centerY = canvasHeight.value / 2;
  const radius = Math.min(canvasWidth.value, canvasHeight.value) * 0.35;
  const dimensions = Object.keys(dimensionScores.value);
  const values = Object.values(dimensionScores.value);
  const angleStep = (Math.PI * 2) / dimensions.length;
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制背景网格（5层）
  ctx.strokeStyle = '#e5e7eb';
  ctx.lineWidth = 1;
  
  for (let i = 1; i <= 5; i++) {
    ctx.beginPath();
    const r = (radius / 5) * i;
    
    for (let j = 0; j <= dimensions.length; j++) {
      const angle = angleStep * j - Math.PI / 2;
      const x = centerX + r * Math.cos(angle);
      const y = centerY + r * Math.sin(angle);
      
      if (j === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    }
    ctx.closePath();
    ctx.stroke();
  }
  
  // 绘制轴线
  ctx.strokeStyle = '#d1d5db';
  ctx.lineWidth = 1;
  
  dimensions.forEach((dim, index) => {
    const angle = angleStep * index - Math.PI / 2;
    const x = centerX + radius * Math.cos(angle);
    const y = centerY + radius * Math.sin(angle);
    
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.lineTo(x, y);
    ctx.stroke();
  });
  
  // 绘制数据区域
  ctx.fillStyle = 'rgba(59, 130, 246, 0.2)'; // blue with opacity
  ctx.strokeStyle = '#3b82f6';
  ctx.lineWidth = 2;
  
  ctx.beginPath();
  values.forEach((value, index) => {
    const angle = angleStep * index - Math.PI / 2;
    // 将分数（假设满分40）转换为半径比例
    const maxScore = 40; // 各维度满分
    const ratio = Math.min(value / maxScore, 1);
    const r = radius * ratio;
    const x = centerX + r * Math.cos(angle);
    const y = centerY + r * Math.sin(angle);
    
    if (index === 0) {
      ctx.moveTo(x, y);
    } else {
      ctx.lineTo(x, y);
    }
  });
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
  
  // 绘制数据点
  ctx.fillStyle = '#3b82f6';
  values.forEach((value, index) => {
    const angle = angleStep * index - Math.PI / 2;
    const maxScore = 40;
    const ratio = Math.min(value / maxScore, 1);
    const r = radius * ratio;
    const x = centerX + r * Math.cos(angle);
    const y = centerY + r * Math.sin(angle);
    
    ctx.beginPath();
    ctx.arc(x, y, 4, 0, Math.PI * 2);
    ctx.fill();
  });
};

// ==================== Lifecycle ====================

onMounted(() => {
  updateCanvasSize();
  animateScore();
  nextTick(() => {
    drawRadarChart();
  });
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    updateCanvasSize();
    nextTick(() => {
      drawRadarChart();
    });
  });
});

watch(() => props.scoreBreakdown, () => {
  animateScore();
  nextTick(() => {
    drawRadarChart();
  });
}, { deep: true });
</script>

<style scoped>
/* 分数动画 */
@keyframes scoreReveal {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.text-7xl {
  animation: scoreReveal 0.6s ease-out;
}
</style>
